<?php 

class Ext_Blog_Validate_Adapter_Domain extends Ext_Blog_Validate_Abstract
{
    protected $_messager;
    const DOMAIN_EXISTS              = 'blogDomainExists';
    const DOMAIN_FORMAT_ERROR        = 'blogDomainFormatError';
    protected $_messageTemplates = array(
        self::DOMAIN_EXISTS              => "This blog domain already exists.",
        self::DOMAIN_FORMAT_ERROR        => "This blog domain format error.",
    );
    
    public function __construct($domain)
    {
        $this->_domain   = $domain;
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }
    
    public function isValid()
    {
        $validator = new Zend_Validate_Regex("/^[a-zA-Z0-9-_]+$/si");
        $validator->setMessage($this->_messageTemplates[self::DOMAIN_FORMAT_ERROR], Zend_Validate_Regex::NOT_MATCH);

        $validatorChain = new Zend_Validate();
        $validatorChain
            ->addValidator(new Zend_Validate_NotEmpty(), true)
            ->addValidator($validator, true)
            ->addValidator(new Zend_Validate_StringLength(2, 22), true)
            ;
        
        if(!$validatorChain->isValid($this->_domain)) {
            $this->addMessages('Blog domain', $validatorChain->getMessages());
            return false;
        }
        
        $auth = Ext_Auth::getInstance();
        $userId = $auth->getIdentity();
        
        $blogDomainOne = App_Model_DbTable_Blog_Domain::getInstance()->getRowByDomain($this->_domain);
        if(isset($blogDomainOne['userId'])){
            if($blogDomainOne['userId'] != $userId){
                $this->addMessage($this->_messager->createMessage(self::DOMAIN_EXISTS));
                return false;
            }
        }
        
        return true;
    }
}
